package com.martin.dms.web.beans;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import org.springframework.binding.message.MessageBuilder;
import org.springframework.binding.message.MessageContext;
import org.springframework.binding.validation.ValidationContext;

import com.martin.dms.model.Category;
import com.martin.dms.model.Item;

public class CategoryBean implements Serializable {

    /**
     * 
     */
    private static final long serialVersionUID = 4413191943616729695L;

    private Long id;
    private String name;
    
    private List<ItemBean> items = new ArrayList<ItemBean>();
    
    private List<Long> itemIds = new ArrayList<Long>();
    
    public CategoryBean() {
    }
    
    public CategoryBean(Category category, boolean copyItems) {
        this.id = category.getId();
        this.name = category.getName();
        if (copyItems) {
            Set<Item> categoryItems = category.getItems();
            for (Item item : categoryItems) {
                items.add(new ItemBean(item.getId(), item.getName()));
            }
        }
    }
    
    public void setId(Long id) {
        this.id = id;
    }
    public Long getId() {
        return id;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getName() {
        return name;
    }

    public void setItems(List<ItemBean> items) {
        this.items = items;
    }

    public List<ItemBean> getItems() {
        return items;
    }

    public void setItemIds(List<Long> itemIds) {
        this.itemIds = itemIds;
    }

    public List<Long> getItemIds() {
        return itemIds;
    }
    
    public void validateCategoriesForm(ValidationContext validationContext) {
        MessageContext messageContext = validationContext.getMessageContext();
        String userEvent = validationContext.getUserEvent();
        if (userEvent.equals("save")) {
            if (name == null || "".equals(name)) {
                messageContext.addMessage(new MessageBuilder().error().code("error.emptyfield.name").build());
            }
        }
    }
}
